package com.nanosn.coffeemaker.databaseproject.persistence;

import com.nanosn.coffeemaker.project.ProjectSettings;
import com.nanosn.coffeemaker.project.ProjectSettingsFactory;
import java.util.HashMap;
import java.util.Map;
import org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl;

/**
 *
 * @author selkhateeb
 */
public class DatabaseJDBCConfiguration extends JDBCConfigurationImpl {

    private static String DERBY = "DERBY";
    private static Map<String, String> AVAILABLE_ENGINES;

    //Initialize AVAILABLE_ENGINES
    static {
        AVAILABLE_ENGINES = new HashMap<String, String>();
        AVAILABLE_ENGINES.put(DERBY, "org.apache.derby.jdbc.EmbeddedDriver");
    }

    public DatabaseJDBCConfiguration() throws Exception {

        ProjectSettings settings = ProjectSettingsFactory.getInstance();
        this.setConnectionDriverName(getDriverName(settings.getDatabaseEngine()));
        this.setConnectionURL(generateConnectionURL(settings));

        this.setMetaDataFactory("jpa");
        this.setLogFactory(new CustomLogFactory());


    }

    private String getDriverName(String engine)
            throws UnknownEngineNameException,
                   EngineNameNotSpecifiedException {

        if (engine == null || engine.trim().equals("")) {
            throw new EngineNameNotSpecifiedException("No Engine Name specified");
        }
        String value = AVAILABLE_ENGINES.get(engine.toUpperCase());
        if (value == null) {
            throw new UnknownEngineNameException("Cannot find driver for enging [" + engine + "]");
        }
        return value;
    }

    /**
     * TODO: this method only works for derby embedded
     * @param settings
     * @return
     */
    protected String generateConnectionURL(ProjectSettings settings) throws UnknownEngineNameException {
        String engine = settings.getDatabaseEngine();
        String host = settings.getDatabaseHost();
        String port = settings.getDatabasePort();
        String name = settings.getDatabaseName();
        String user = settings.getDatabaseUserName();
        String password = settings.getDatabasePassword();

        String value = AVAILABLE_ENGINES.get(engine.toUpperCase());
        if (value == null) {
            throw new UnknownEngineNameException("Cannot find driver for enging [" + engine + "]");
        }

        return "jdbc:" + engine.trim() + ":" + name + ";create=true";
    }
}
